import Request from 'utils/request';

import ShopGoods from 'models/classify/shopGoods';

export default class SearchGoodsApi {
  static getSearchLabelList() {
    const apiName = 'api/wehcatshop/getSearchLog';

    return Request.post(apiName).then(res => {
      res = res.data;
      let listMost = res.listMost;
      let hotSearchList = [];
      for (let i = 0; i < listMost.length; i++) {
        const obj = listMost[i];
        let data = {
          id: obj.searchLogId,
          text: obj.searchContent
        };

        if (i === 0) {
          data.type = 'hot-first';
        } else if (i === 1) {
          data.type = 'hot-second';
        } else if (i === 2) {
          data.type = 'hot-third';
        }
        hotSearchList.push(data);
      }

      let mineSearchLog = res.mineSearchLog;
      let historyRecordList = [];
      for (let i = 0; i < mineSearchLog.length; i++) {
        const obj = mineSearchLog[i];

        historyRecordList.push({
          id: obj.searchLogId,
          text: obj.searchContent
        });
      }

      return {
        hotSearchList,
        historyRecordList
      };
    });
  }

  static clearHistory() {
    const apiName = 'api/wehcatshop/delSearchLog';

    return Request.post(apiName).then(res => {
      return res.msg
    });
  }

  static getSearchGoods(searchValue, pagination, params) {
    const apiName = 'api/wehcatshop/getGoodsListBygoodsName';

    let postData = {
      goodsName: searchValue,
      limit: pagination.pageSize,
      page: pagination.currentPage
    };

    let partnerId = params.partnerId;
    if (partnerId !== undefined) {
      postData.partnerId = partnerId;
    } else {
      let branchId = params.branchId;
      if (branchId !== undefined) {
        postData.branchId = branchId;
      }
    }

    return Request.post(apiName, postData).then(res => {
      let goodsList = res.data;
      let goodsArr = [];
      for (let i = 0; i < goodsList.length; i++) {
        let goods = goodsList[i];
        goods = new ShopGoods(goods);
        goodsArr.push(goods);
      }
      pagination.totalCount = res.rows;
      return goodsArr;
    });
  }
}
